/**
 * Author: huangzhiyang
 * Date: 2016/12/1 9:52
 * Description: ""
 */
require("../common/common.scss");
require("./index.scss");

var dialog = require('COMMON/modules/dialog-simple');

var loading = require('COMMON/js/util.loading.pc.js');

var Toast = require('COMMON/modules/Toast');
var toast = new Toast;
var UrlData = require("../common/zft.url.data");
var UrlParse = require('COMMON/js/util.url.parse.query.js');

var ParseTemplate = ZFT.Util.ParseTemplate;
var Template = {
	li: ParseTemplate(require("./tpl/li.xtpl")),
	form: ParseTemplate(require("./tpl/form.xtpl")),
	dialogheader: ParseTemplate(require("./tpl/dialogheader.xtpl")),
	banklist: ParseTemplate(require("./tpl/banks.xtpl")),
	limit:ParseTemplate(require("./tpl/limit.xtpl"))
};

var Main = ZFT.Util.Class({
	dom: {
		feeDetail: '#feeDetail',
		feeDetailList: '#feeDetailList',
		fee: '#fee',
		accbalance: '#viaAccBalance',
		wepay: '#viaWepay',
		alipay: '#viaAlipay',
		dialog: {
			qrcode: 'dialogQrcode',
			accbalance: 'dialogAccbalance'
		},
		bankList: '#bankList',
		fuyoupay: '#viaFuyoupay',
		bankitems: '.ico-bank-items'
	},
	bank_code: [
		'0801020000', '0801030000', '0801040000', '0801050000', '0803010000', '0801000000',
		'0803080000', '0803100000', '0803030000', '0803050000', '0803020000', '0803060000',
		'0803040000', '0803090000', '0000000000',
	],
	FEE_TYPE: {
		'house_fee': '房租',
		'water_fee': '水费',
		'property_fee': '物业费',
		'power_fee': '电费',
		'gt_water_fee': '公摊水费',
		'gt_power_fee': '公摊电费',
		'tax_fee': '税费',
		'other_fee':'其他费用',
		'favor_fee':'优惠金额'
	},

	AJAX_URLS: {
		feeDetailList: {
			rent: '/r/BillManager_getTotalMoney', // 租赁账单明细 type : 1
			trust: '/r/BillManager_trustPayTotal' // 托管账单明细 type : 2
		},

		getAccBalance: '',
		payViaAccBalance: '/r/pay_payByBalance',
		payViaWepay: '',
		payViaAlipay: {
			rent: '/r/pay_payLeaseByAlipay', // 支付宝支付-租赁账单 type : 1
			trust: '/r/pay_payTrustByAlipay' // 支付宝支付-托管账单 type : 2
		},
		payViaTongLian: '/r/pay_payByTongLian',  //通联支付,
		payViaMinSheng:'/r/Pay_payByCmbc',//民生支付
		checkOrderStatus: '/r/BillManager_getPayStatus'
	},

	interval: {
		timer: null,
		time: 1000
	},

	xhr: null,
	xhrChkStatus: null,
	contract_ids: null,
	pay_params: {},

	init: function () {
		var _this = this;

		var dom = _this.dom;

		var url = window.location.href,
			urlParam = UrlParse(url);

		if (urlParam.id) {

			this.pay_params.type = urlParam.type;
			this.contract_ids = this.pay_params.order_num = urlParam.id;
			this.pay_params.begin_cycle = urlParam.begin;
			this.pay_params.end_cycle = urlParam.end;
			this.pay_params.order_id=JSON.stringify(urlParam.order_id.split(","));

		} else {
			ZFT.Util.STip('fail', '未选中账单');
			return false;
		}

		//
		if (this.pay_params.type == 2) {
			$(this.dom.feeDetail).css({ display: 'none' });
		}

		_this.ajaxGetFeeDetailList(_this.contract_ids, _this.pay_params.type);

		$(dom.accbalance).on('click', function () {
			$(dom.bankList).html("");
			if (_this.pay_params.money) {
				_this.showDialog('accbalance', _this.contract_ids, $(_this.dom.fee).text());
			}
		});


		$(dom.wepay).on('click', function () {
			$(dom.bankList).html("");
			if (_this.pay_params.money) {
				_this.showDialog('wepay', _this.contract_ids, $(_this.dom.fee).text());
			}
		});

		$(dom.alipay).on('click', function () {
			$(dom.bankList).html("");
			if (_this.pay_params.money) {
				_this.showDialog('alipay', _this.contract_ids, $(_this.dom.fee).text());
			}
		});
		$(dom.fuyoupay).on('click', function () {
			var html = Template.banklist({ banlist: _this.bank_code });
			$(dom.bankList).html(html);
			$(dom.bankList+" .u-bank_tab").on("click",function(e){
				var tarTab=$(e.currentTarget);
				var type=tarTab.attr("data-type");
				if(tarTab.hasClass("active")) return false;
				tarTab.addClass("active").siblings().removeClass("active");
				$("#b2cBanks").attr("data-type",type);
				/*$("#b2cBanks").css("display",(type==1) ? "block" : "none");
				$("#b2bBanks").css("display",(type==2) ? "block" : "none");*/
			})
			
			$(dom.bankitems).on('click', function (e) {
				var tarBtn = $(e.currentTarget);
				var code = tarBtn.attr("data-code");
				var type=$("#b2cBanks").attr("data-type");
				_this.ajaxSendDataToFuyou(code,type);
			})
		});
		$("#viewDtl").on("click",function(){
			var html=Template.limit();
			$("#modal").html(html);
		});
		$("#modal").on("click",".close",function(e){
			var tarBtn = $(e.currentTarget);
            tarBtn.parents(".m-modal_bg").fadeOut(200);
		})
	},

	// 初始化数据
	ajaxGetFeeDetailList: function (contractIds, type) {
		var _this = this;

		var url = type == 1 ? _this.AJAX_URLS.feeDetailList.rent : _this.AJAX_URLS.feeDetailList.trust;

		var param = type == 1 ? { ordernum: contractIds } : { id: contractIds };

		param.begin_cycle = this.pay_params.begin_cycle;
		param.end_cycle = this.pay_params.end_cycle;
		param.status = 0;
		param.order_id=this.pay_params.order_id;
		ZFT.Util.Ajax(url, {
			type: 'POST',
			params: param,
			loading: function () { },
			success: function (res) {

				if (res.code == 200) {

					type == 1 && _this.renderFeeDetailList(res.data);
					$(_this.dom.fee).text(res.data.total_fee || res.data.should_pay);

					_this.pay_params = $.extend({}, _this.pay_params, {
						mid: res.data.mid || res.data.tenant_id,
						money: res.data.total_fee || res.data.should_pay
					});

					// var ajaxUrl = type == 1 ? _this.AJAX_URLS.payViaAlipay.rent : _this.AJAX_URLS.payViaAlipay.trust;
					// $( _this.dom.alipay ).attr({
					// 	href: ajaxUrl + '?order_num=' + _this.pay_params.order_num + '&mid=' + _this.pay_params.mid + '&begin_cycle=' + _this.pay_params.begin_cycle + '&end_cycle=' + _this.pay_params.end_cycle + '&money=' + _this.pay_params.money,
					// 	target: '_blank'
					// });

				} else if (res.code == 400) {

					ZFT.Util.STip('fail', res.msg);
					window.history.go(-1);

				} else {

					ZFT.Util.STip('fail', res.msg);

				}
			},
			serverError: function (xhr, txt) {
				ZFT.Util.STip('fail', txt);
			}
		})
	},
	showDialog: function (target, contract_ids, fee) {
		var _this = this;

		// var dialogBalance;

		switch (target) {
			case 'accbalance':
				_this.ajaxSendData({
					url: _this.AJAX_URLS.payViaAccBalance,
					params: _this.pay_params,
					loading: {
						text: '支付中...'
					},
					success: function (res) {
						if (res.code == 200) {
							ZFT.Util.STip('fail', res.msg);
							setTimeout(function () {
								history.go(-1);
							}, 3);
						} else {
							ZFT.Util.STip('fail', res.msg);
						}
					}
				});
				// dialogBalance = new dialog({
				// 	header: Template.dialogheader({ title: '平台账号余额支付' }),
				//  	width: 560,
				//  	height: 260,
				//  	content: '<div id="'+ _this.dom.dialog.accbalance +'"></div>',
				//  	onOpenAfter: function(){
				//  		_this.ajaxRenderData({
				//  			container: 	'#' + _this.dom.dialog.accbalance,
				//  			url: 		_this.AJAX_URLS.getAccBalance,
				//  			loading: 	{ tag: 'div', id: 'dialogLoading' },
				// 			success: function(res) {
				// 				var html = Template.form({ balance: res.data, fee: fee });
				// 					$('#' + _this.dom.dialog.accbalance).html(html);

				// 					if(_this.compareFloat( res.data, fee )) {
				// 						$('#' + _this.dom.dialog.accbalance).append('<div class="t-center"><a id="btnConfirmPay" href="javascript:;" class="btn btn-default">确认支付</a></div>');

				// 						$(document).on('click', '#btnConfirmPay', function(){
				// 							dialogBalance.close();
				// 							_this.ajaxPayViaAccBalance({
				// 								contract_ids: contract_ids,
				// 								success: function ( res ) {
				// 									location.href= 'appcenter_paysuccess.html?ordernum=' + res.data.order_no
				// 								}
				// 							});
				// 						})
				// 					} else {
				// 						$('#' + _this.dom.dialog.accbalance).append('<div class="t-center"><a target="_blank" href="/recharge.html" class="btn btn-default">余额不足去充值</a></div>');
				// 					}
				// 			}
				//  		});
				//  	},
				//  	onCloseAfter: function(){
				//  		dialogBalance.remove();
				//  		dialogBalance = null;
				//  		$(document).off('click', '#btnConfirmPay');
				//  	}
				// });
				// dialogBalance.open();
				break;

			case 'wepay':
				_this.ajaxPayViaQrcode('wepay', contract_ids, fee);
				break;

			case 'alipay':
				_this.ajaxPayViaQrcode('alipay', contract_ids, fee);
				break;
		}
	},
	ajaxPayViaAccBalance: function (opts) {
		this.ajaxSendData({
			url: _this.AJAX_URLS.payViaAccBalance,
			params: {
				module_id: opts.module_id,
				price_id: opts.price_id
			},
			loading: { text: '正在处理中' },
			success: function (res) {
				opts.success && opts.success(res);
			},
			error: function (res) {
				opts.error && opts.error(res);
			}
		});
	},
	ajaxPayViaQrcode: function (method, contract_ids, fee) {
		var _this = this;

		var dialogTitle,
			colorSaoyisao,
			ajaxUrl;

		switch (method) {
			case 'wepay':
				dialogTitle = '微信支付';
				colorSaoyisao = '#45D445';
				ajaxUrl = _this.AJAX_URLS.payViaWepay;
				break;
			case 'alipay':
				dialogTitle = '支付宝支付';
				colorSaoyisao = '#0797d9';
				ajaxUrl = _this.pay_params.type == 1 ? _this.AJAX_URLS.payViaAlipay.rent : _this.AJAX_URLS.payViaAlipay.trust;
				break;
		}

		var dialogQrcode = new dialog({
			header: Template.dialogheader({ title: dialogTitle }),
			width: 560,
			height: 350,
			content: '<div id="' + _this.dom.dialog.qrcode + '" style="margin-top:46px;padding:20px 30px;text-align:center;"></div>',
			onOpenAfter: function () {
				// 弹窗打开后发送ajax请求并根据返回值生成二维码
				// 循环请求订单状态（每次请求订单状态complete时再发送下一个请求）
				_this.xhr = _this.ajaxRenderData({
					container: '#' + _this.dom.dialog.qrcode,
					//url:($("#payType").val()==1) ? _this.AJAX_URLS.payViaTongLian : _this.AJAX_URLS.payViaMinSheng,  //通联
					//url: _this.AJAX_URLS.payViaMinSheng,  //民生
					url: _this.AJAX_URLS.payViaTongLian,
					params: {
						order_num: _this.pay_params.order_num,
						mid: _this.pay_params.mid,
						begin_cycle: _this.pay_params.begin_cycle,
						end_cycle: _this.pay_params.end_cycle,
						money: _this.pay_params.money,
						order_type: _this.pay_params.type,
						pay_type: (method == 'wepay') ? 2 : 1,
						order_id:_this.pay_params.order_id
					},
					loading: {
						id: 'dialogLoading'
					},
					success: function (res) {
						_this.ordernum = res.data.order_no;

						if (_this.canvasSupport()) {
							$('#' + _this.dom.dialog.qrcode).qrcode({ width: 165, height: 165, text: res.data.url });
						} else {
							$('#' + _this.dom.dialog.qrcode).qrcode({ render: "table", width: 165, height: 165, text: res.data.url });
							$('#' + _this.dom.dialog.qrcode).wrapInner('<div style="padding-left:167px;"></div>');
						}
						$('#' + _this.dom.dialog.qrcode).prepend('<div class="t-center f14 mb20">应付金额：<em class="c-warning">' + fee + '</em>元</div>');
						$('#' + _this.dom.dialog.qrcode).append('<div class="t-center f16 mt20 pt10 border-t border-d" style="line-height:32px"><i class="icon-u-bold icon-saoyisao" style="color:' + colorSaoyisao + ';font-size:30px;vertical-align:top;"></i> 扫码完成支付</div>');


						_this.checkOrderStatus({
							params: {
								order_num: _this.pay_params.order_num,
								begin_cycle: _this.pay_params.begin_cycle,
								end_cycle: _this.pay_params.end_cycle,
								type: _this.pay_params.type
							},
							success: function (res) {
								if (res.code == 200 && res.data.status == 1) {

									$('#' + _this.dom.dialog.qrcode).html('<div class="t-center f20 c-warning">' + res.msg + '</div><div id="countdown"></div>');

									clearInterval(_this.interval.timer);

									var countdownTime = 3;

									var timer = setInterval(function () {
										$('#countdown').html(countdownTime + '秒返回账单列表');
										countdownTime--;
										if (countdownTime == 0) {
											clearInterval(timer);
											history.go(-1);
										}
									}, 1000);
								}

								if (res.code == 403) {
									// 支付失败
									$('#' + _this.dom.dialog.qrcode).html('<div class="t-center f20 c-warning" style="padding-top: 60px;">支付失败</div><div class="t-center f20 c-warning" style="padding-top: 60px;"><a href="javascript:;" class="btn btn-default" onclick="location.reload()">重新支付</a></div>');
									clearInterval(_this.interval.timer);
								}

								if (res.code == 400) {
									// 查询异常
									$('#' + _this.dom.dialog.qrcode).html('<div class="t-center f20 c-warning" style="padding-top: 60px;">支付失败</div><div class="t-center f20 c-warning" style="padding-top: 60px;"><a href="javascript:;" class="btn btn-default" onclick="location.reload()">重新支付</a></div>');
									clearInterval(_this.interval.timer);
								}
							}
						});
					},
					error: function (res) {
						dialogQrcode.close();
					}
				})
			},
			onCloseAfter: function () {
				_this.ordernum = null;
				if (_this.xhr && _this.xhr.readyState != 4) {
					_this.xhr.abort();
				}
				clearInterval(_this.interval.timer);
				dialogQrcode.remove();
				dialogQrcode = null;
			}
		});
		dialogQrcode.open();
	},
	checkOrderStatus: function (opts) {
		var _this = this;
		_this.interval.timer = setInterval(function () {
			if (!_this.xhrChkStatus || _this.xhrChkStatus.readyState == 4) {
				_this.xhrChkStatus = _this.ajaxCheckOrderStatus({
					params: opts.params,
					success: function (res) {
						opts.success(res);
					}
				});
			}
		}, _this.interval.time)
	},
	ajaxCheckOrderStatus: function (opts) {
		return ZFT.Util.Ajax(this.AJAX_URLS.checkOrderStatus, {
			type: 'POST',
			params: opts.params,
			success: function (res) {
				opts.success && opts.success(res);
			},
			serverError: function (xhr, txt) {
				// ZFT.Util.STip( 'fail',txt );
			}
		})
	},
	ajaxRenderData: function (opts) {
		return ZFT.Util.Ajax(opts.url, {
			type: 'POST',
			params: opts.params,
			loading: function () {
				var loadingOpts = {};

				loadingOpts.id = opts.loading.id;
				loadingOpts.text = opts.loading.text || '';
				loadingOpts.className = opts.loading.className;
				if (opts.loading.tag == 'tr') {
					loadingOpts.colspan = opts.loading.colspan ? opts.loading.colspan : '';
				}

				var html = loading(opts.loading.text, loadingOpts);
				$(opts.container).html(html);
			},
			success: function (res) {
				$('#' + opts.loading.id).remove();


				if (res.code == 200 || res.code == 'success') {
					opts.success && opts.success(res);
				} else {
					ZFT.Util.STip('fail', res.msg);
					opts.error && opts.error(res);
				}
			},
			serverError: function (xhr, txt) {

			}
		})
	},
	ajaxSendData: function (opts) {
		/*
			opts: {
				url:
				params:
				loading: {
					text
				}
				success: fn
			}
		 */
		return ZFT.Util.Ajax(opts.url, {
			type: 'POST',
			params: opts.params,
			loading: function () {
				toast.show('loading', opts.loading.text);
			},
			success: function (res) {
				toast.hide();

				if (res.code == 200) {
					opts.success && opts.success(res);
				} else {
					ZFT.Util.STip('fail', res.msg);
					opts.error && opts.error(res);
				}
			},
			serverError: function (xhr, txt) {

			}
		})
	},

	renderFeeDetailList: function (data) {
		var tempArr = [];

		for (var item in data) {
			if (this.FEE_TYPE[item]) {
				tempArr.push({
					name: this.FEE_TYPE[item],
					fee: data[item]
				});
			}
		}

		var html = Template.li({ data: tempArr });
		$(this.dom.feeDetailList).html(html);
	},

	compareFloat: function (num1, num2) {
		// num1 num2 必须为数字或数字字符串
		var num1 = parseFloat(num1).toFixed(2),
			num2 = parseFloat(num2).toFixed(2);

		return num1 * 100 >= num2 * 100;
	},
	canvasSupport: function () {
		return !!document.createElement('canvas').getContext;
	},

	//富友接口
	ajaxSendDataToFuyou: function (code,type) {
		var _this = this;
		var tarUrl = "";
		var params = _this.pay_params;
		var host = window.location.host;
		var http = window.location.protocol + "//";
		var home = http + host + "/index/index/home?tar=";
		var newWindow= window.open("about:blank", "_blank");
		var dType = "" + ZFT.Util.getDtype();
		if (!code) return false;
		if (UrlData.hasOwnProperty(dType)) tarUrl = home + UrlData[dType];
		var Url = "?type=" + params["type"] + "&order_num=" + params["order_num"] + "&begin_cycle=" + params["begin_cycle"] + "&end_cycle=" + params["end_cycle"] + "&mid=" + params["mid"] + "&money=" + params["money"] + "&bank_type=" + code + "&url=" + tarUrl + "&order_id="+params["order_id"] + "&pay_type="+ type;
		//console.log(Url)
		ZFT.Util.Ajax("/r/pay_payByFuYouCheck" + Url, {
			type: "GET",
			dataType: "json",
			success: function (res) {
				if (res.code == 200) {
					var URL = "/r/pay_payByFuYou" + Url;
					newWindow.blur();
					newWindow.opener.focus();
					newWindow.location=URL;
				} else if (res.code == 102) {
					return ZFT.Util.STip("fail", "未登录,请重新登录", 5000, function () {
						window.location.href = "/index/index/login";
					});
				}else if(res.code==207){
					return ZFT.Util.STip("fail", res.msg, 5000, function () {
						history.go(-1);
					});
				}else {
					return ZFT.Util.STip("fail", res.msg, 5000);
				}
			}
		})


	},

});

$(function () {
	new Main();
})